package com.wehealth;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.wehealth.dm.User;
import com.wehealth.util.DataManger;
import com.wehealth.util.GetUrl;
import com.wehealth.widget.LineEditText;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class Login extends Fragment{

	private MainActivity mContext;
	private User user;
	private LineEditText  mAccountEt;
	private LineEditText  mPswEt;
	private String account;
	private String psw;
	private DataManger mdatamanger;
	private static  String JSONResult;
	private ProgressBar mProgress;
	private static final int NET_ERROR = -100;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return  inflater.inflate(R.layout.login, null);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		
		mContext =(MainActivity)getActivity();

		mdatamanger = mContext.getDataManger();
		
		mProgress =(ProgressBar)mContext.findViewById(R.id.login_progress);
		
		mAccountEt =(LineEditText)mContext.findViewById(R.id.login_user_edit);
		mPswEt =(LineEditText)mContext.findViewById(R.id.login_psw_edit);
		
		
		TextView register = (TextView)mContext.findViewById(R.id.login_register_tx);
		register.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub		
				Register  registerView = new Register();
					mContext.switchContent(registerView);			
			}
		});
		
		TextView findpsw = (TextView)mContext.findViewById(R.id.login_find_psw);
		findpsw.setOnClickListener( new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				FindPSW  findpswView = new FindPSW();
				mContext.switchContent(findpswView);			
				
			}
		});
		
		
		
		Button bBack = (Button) mContext.findViewById(R.id.login_cancel);
			
		 bBack.setOnClickListener(new View.OnClickListener()
			{
				public void onClick(View v)
				{               
				    mContext.switchContentHome();
				}
			});
		 
		 
		 Button  loginBt =(Button)mContext.findViewById(R.id.login_submit_bt);
		 loginBt.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
			    mProgress.setVisibility(View.VISIBLE);
				 LoginToConnServer();
			}
		});
		
		
	}

	
//	private void openLoginDialog(final boolean result){
//	    AlertDialog.Builder builder = new AlertDialog.Builder(mContext); 
//	    builder.setIcon(null);
//	    String login_result = mContext.getString(R.string.login_success);
//	    if(result){
//	    	login_result = mContext.getString(R.string.login_success);
//	    }else{
//	    	login_result = mContext.getString(R.string.login_fail);
//	    }
//	    builder.setTitle(login_result);
//	    
//	    builder.setPositiveButton("确定", new AlertDialog.OnClickListener() {
//			@Override
//			public void onClick(DialogInterface arg0, int arg1) {
//				// TODO Auto-generated method stub
//				 if(result){
//						Home vHome = new Home();
//						mContext.switchContent(vHome);	
//						mContext.updateMenuSide();
//				 }
//			}
//	    	
//	    });
//	    builder.create().show();
//		
//	}
	
	
	private void  LoginToConnServer(){
			new Thread(){
				@Override
				public void run(){
					try {
						initDataFromNet();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				handler.sendEmptyMessage(0);
				}
				}.start();
	}
	
	
	private void initDataFromNet() throws IOException{
		 String urlAPI = GetUrl.Login_Url();
		 HttpPost httpRequest= new HttpPost(urlAPI);
		 
		 List <NameValuePair> params = new ArrayList <NameValuePair>();
		 account = mAccountEt.getText().toString().trim();
		 psw = mPswEt.getText().toString().trim();
		 
		 params.add(new BasicNameValuePair("loginname",account));
		 params.add(new BasicNameValuePair("password",psw));
		 
		 try{
			 httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
			 HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
			 if(httpResponse.getStatusLine().getStatusCode() == 200)
			 {
				 JSONResult = EntityUtils.toString(httpResponse.getEntity());
			 }
		 } catch(Exception e){
			 Log.e("SIMMON:",  e.toString());
		 }
	
	}
	
	private Handler handler =new Handler(){
		@Override
		public void handleMessage(Message msg){
		    super.handleMessage(msg);
    		if(JSONResult!=null){
    		    BindNewsData(JSONResult);
    		}else{
    		    mProgress.setVisibility(View.GONE);
    		    openLoginDialog(NET_ERROR);
    		}
		}
	};
	
	private void BindNewsData(String strJSON){
		try{
				JSONObject jsonObject = new JSONObject(strJSON);
				String result_str = jsonObject.getString("result");
				Log.d("SIMMON"," result_str="+result_str);
			    int result = Integer.valueOf(result_str);
			    Log.d("SIMMON"," result="+result);
			    openLoginDialog(result);
			    
	    }catch(JSONException ex)
	    {
	    		Log.e("JSON Error: ", ex.toString()); 
	    }
		
	}
	
//	private void ServerResult(int result){
//		user = mContext.getUserInfo();
//	
//		boolean loginResult = false;
//		if((account.equals(user.getAccount())||account.equals(user.getPhoneNumber()))&& psw.equals(user.getPassword())){
//			loginResult = true;	
//		}
//		openLoginDialog(loginResult);
//	}
	
	private void openLoginDialog(final int result){
		 user = mContext.getUserInfo();
		 String login_result = mContext.getString(R.string.login_success);
		switch (result) {
			case -1:
				login_result = mContext.getString(R.string.login_fail);
				break;
			case 0:
				login_result = mContext.getString(R.string.login_fail);
				break;
			case -100:
			    login_result = mContext.getString(R.string.net_connet_fail);
			    break;
			default:
			    if(result > 0){
			    	login_result = mContext.getString(R.string.login_success);
			    	user.setUserId(result);
			    	user.setAccount(account);
			    	user.setPassword(psw);
			    	mdatamanger.delUserDate();
			    	mdatamanger.storeUserInfo(user);
			    }else{
			    	login_result = mContext.getString(R.string.login_fail);
			    }
				break;
		}
	    AlertDialog.Builder builder = new AlertDialog.Builder(mContext); 
	    builder.setIcon(null);
	    builder.setTitle(login_result);
	    
	    builder.setPositiveButton("确定", new AlertDialog.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				 if(result > 0){
					    mContext.updateMenuSide();   
						Home vHome = new Home();
						mContext.switchContent(vHome);	
				 }
			}
	    	
	    });
	    mProgress.setVisibility(View.GONE);
	    builder.create().show();
		
	}
	
}
